package com.gitee.c0dehvb.reactive.sample.r2dbc.metadata;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.spi.database.type.DatabaseType;
import org.apache.shardingsphere.underlying.common.database.type.DatabaseTypes;
import org.apache.shardingsphere.underlying.common.database.type.dialect.MySQLDatabaseType;

import java.util.HashMap;
import java.util.Map;

/**
 * R2dbcSchemaMetaDataLoader静态工厂
 * @author LiYilin
 * @since 2022/6/16 3:18 PM
 **/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class R2dbcSchemaMetaDataLoaderFactory {
    private static final Map<String, R2dbcSchemaMetaDataLoader> META_DATA_LOADER_MAP;

    static {
        META_DATA_LOADER_MAP = new HashMap<>();
        META_DATA_LOADER_MAP.put(new MySQLDatabaseType().getName(), new MySQLR2dbcSchemaMetaDataLoader());
    }

    public static R2dbcSchemaMetaDataLoader buildByDatabaseType(DatabaseType databaseType) {
        return META_DATA_LOADER_MAP.get(databaseType.getName());
    }

    public static R2dbcSchemaMetaDataLoader buildByUrl(String url) {
        // 复用Sharding 4.x代码，目前仅支持对jdbc连接分析
        url = url.replace("r2dbcs", "jdbc")
                .replace("r2dbc", "jdbc");
        DatabaseType databaseType = DatabaseTypes.getDatabaseTypeByURL(url);
        return databaseType != null ? buildByDatabaseType(databaseType) : null;
    }
}
